<?php
namespace app\api\controller;
use app\admin\model\BaseSetting;
use app\api\controller\user\Dealer;
use app\api\model\User;
use app\common\model\dealer\Capital;
use app\common\model\user\BalanceLog;
use app\common\exception\BaseException;
use app\common\library\wechat\Abonus;
use app\common\library\wechat\WxPay;
use app\common\model\Wxapp as WxappModel;
use think\Db;
use org\RabbitMQ;
use org\Redis;
use utils\Services;
/**
 *  分红队列
 * Class BackAbonusAccounts
 * @package app\task\queue
 */
class Backabonus extends \think\Controller
{


    protected function log($pre,$data = null)
    {
        if($data) {
            $data = is_array($data) ? json_encode($data) : $data;
            file_put_contents("fenhong-".date('Ymd', time()).".log",  $pre . $data .  "\n", FILE_APPEND);
        } else {
            file_put_contents("fenhong-".date('Ymd', time()).".log",  $pre .  "\n", FILE_APPEND);
        }

    }

    public function getBackAbonus(){
        $rmq = new RabbitMQ;
        $processMessage = function ($envelope, $queue) {
            try{
                $this->log('101 分红队列逻辑开始: ');
                $msg = $envelope->getBody();
                $this->log('1-1 分红队列逻辑开始:');
                $params= json_decode($msg,true);
                $this->log('1-2 接口入参: ', $params);
                $order=$this->getOrderInfo($params['orderId']);//获取订单信息
                $this->log('1-3 接口订单入参: ', $order);

                $setting=$this->getWxappSetting($order['wxapp_id']);//获取本次分红设置
                $this->log('1-4 设置信息: ', $setting);
                $Abonus=new Abonus($order['wxapp_id']);
                //最后一个人的分红
                $lastUser=$this->getLastUser($setting);
                $this->log('1-5 最后一笔订单信息: ',$lastUser);
                if(empty($lastUser)){
                    $this->log('1-6 最后一笔订单不存在: ');
                    /***当最后一条订单的出局数据不存在的时候**/
                    if($setting['start_time']>$order['pay_time'] || $setting['status']==2 ){
                        $this->log('1-6-1 不给用户分: ');
                        /**只给商户和系统分红**/
                        //如果支付金额小于设置金额或者未开启分红，只给系统和商户分账
                        $periods_num=0;
                        //写入分红系统平台得信息
                        $this->log('1-6-1-2 写入分红系统平台得信息: 开始...');
                        $this->setSystemAccounts($order,$periods_num);
                        $this->log('1-6-1-3 写入分红系统平台得信息: 完成');

                        //写入服务商分红信息
                        $this->log('1-6-1-4 写入服务商分红信息: 开始...');
                        $this->setOperateCenterAccounts($order,$periods_num);
                        $this->log('1-6-1-5 写入服务商分红信息: 完成');
                        //写入分红商家得信息11
                        if($order['order_source']==40){
                            $this->log('1-6-1-6 储值卡信息：开始');
                            $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                            $this->log('1-6-1-7 写入服务商分红信息:',$CardSetting);
                            //未设置分红或是未到分红时间，用户分红为0
                            $this->setStoreAccounts(2,0,$order,$CardSetting,$periods_num);
                            $this->log('1-6-1-8 写入服务商分红信息:结束');
                        }elseif($order['order_source']==50 || $order['order_source'] == 10 ){
                            //未设置分红或是未到分红时间，用户分红为0
                            $this->setStoreAccounts(1,0,$order,$setting,$periods_num);
                            $this->log('1-6-1-9 写入服务商分红信息:结束');
                        }

                        $this->log('1-7-1-1 写入分红商家得信息: 完成');
                        //调用分账接口
                        $req=$Abonus->addReceiver();
                        $this->log('1-7-1-2 将服务商添加到 微信端分账接收方结束');
                        if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                            sleep(60);
                            $reault=$Abonus->profitSharings($order);
                            if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                                $this->log('1-7-2-1 系统分账结果',$reault);
                                return true;
                            }else{
                                $this->log('1-7-2-2 系统分账失败结果',$reault);
                                $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                            }
                            $this->log('1-7-2-3 分红结果: ', $reault);

                        }else{
                            $this->log('1-7-2-4 将服务商添加到分账接收方失败');

                        }
                    }else{
                        $this->log('1-7-2-5 不给用户分: ');
                        // 给系统、服务商、商户写入分账数据
                        //写入分红系统平台得信息
                        $this->log('1-7-2-6 写入分红系统平台得信息: 开始...');
                        $this->setSystemAccounts($order,$setting['periods_num']);
                        $this->log('1-7-2-7 写入分红系统平台得信息: 完成');

                        //写入服务商分红信息
                        $this->log('1-7-2-8 写入服务商分红信息: 开始...');
                        $this->setOperateCenterAccounts($order,$setting['periods_num']);
                        $this->log('1-7-2-9 写入服务商分红信息: 完成');
                        //如果开启了分红设置，并且支付金额大于设置的分红金额，满足条件，给所有人分
                        if($order['order_source']==40){
                            $this->log('1-7-3-1 信息:');
                            $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                            $this->log('1-7-3-2 信息:');
                            //当支付时间小于设置结束时间，用户参与分红，
                            if ($setting['end_time']>=$order['pay_time']){
                                $this->log('1-7-3-3 信息:');
                                //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                $userMoney=$this->getUserMoney(2,0,$order,$CardSetting,$setting);//计算用户的分红金额
                                $this->log('1-7-3-4 金额信息:',$userMoney);
                                $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                $this->log('1-7-3-5 信息:');
                            }else{
                                $this->log('1-7-3-6 信息:');
                                //当支付时间大于设置结束时间，本用户不参与分红，给前面的用户分红
                                //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                $userMoney=$this->getUserMoney(2,1,$order,$CardSetting,$setting);//计算用户的分红金额
                                $this->log('1-7-3-8 金额信息:',$userMoney);
                                $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                $this->log('1-7-3-9 信息:');
                            }
                            $this->log('1-7-4-1 计算分红金额:',$userMoney);
                        }elseif($order['order_source']==50 || $order['order_source'] == 10){
                            $this->log('1-7-4-2 信息:');
                            if ($setting['end_time']>=$order['pay_time']){
                                $this->log('1-7-4-3 信息:');
                                //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                $userMoney=$this->getUserMoney(1,0,$order,0,$setting);//计算用户的分红金额
                                $this->log('1-7-4-4 金额信息:',$userMoney);
                                $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                $this->log('1-7-4-5 信息:');
                            }else{
                                $this->log('1-7-4-6 信息:');
                                //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                $userMoney=$this->getUserMoney(1,1,$order,0,$setting);//计算用户的分红金额
                                $this->log('1-7-4-7 金额信息:',$userMoney);
                                $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                $this->log('1-7-4-8 信息:');
                            }
                            $this->log('1-7-4-9 计算分红金额:',$userMoney);
                        }
                        $this->log('1-7-5-0 计算分红金额:',$userMoney);

                        if($setting['end_time']<$order['pay_time']){
                            $this->log('1-7-5-1 不给自己分:开始');
                            /**只给前面的人分红，自己不参与分红**/
                            $this->getNoSelfBackAbonus($order,$setting,$userMoney);
                            $this->log('1-7-5-2 不给自己分:结束');
                        }else{
                            $this->log('1-7-5-3 给自己分:开始');
                            /**给前面的人分红，自己也参与分红**/
                            $this->getMultipleBackAbonus($order,$setting,$userMoney);
                            $this->log('1-7-5-4 给自己分:结束');
                        }

                    }
                }else{
                    $this->log('1-7-5-5 最后一笔订单存在: ');
                    /***当最后一条订单的出局数据存在的时候，以最后一条订单的出局数据计算**/
                    if(empty($lastUser['finish_time']) || $lastUser['finish_time']==0){
                        //当订单进入后，如果支付时间小于开始时间，或者支付时间小于结束时间，或者支付时间小于最后一步订单出局时间，或者开关未开启
                        /***********当结束时间不存在****************/
                        if($setting['start_time']>$order['pay_time']  //支付时间小于开始时间
                            || $setting['end_time']<$order['pay_time'] //支付时间大于结束时间
                            || $setting['status']==2 ){
                            $this->log('1-7-5-6 订单存在: ');
                            /**只给商户和系统分红**/
                            //如果支付金额小于设置金额或者未开启分红，只给系统和商户分账
                            $periods_num=0;
                            //写入分红系统平台得信息
                            $this->log('1-7-5-7 写入分红系统平台得信息: 开始...');
                            $this->setSystemAccounts($order,$periods_num);
                            $this->log('1-7-5-8 写入分红系统平台得信息: 完成');

                            //写入服务商分红信息
                            $this->log('1-7-5-9 写入服务商分红信息: 开始...');
                            $this->setOperateCenterAccounts($order,$periods_num);
                            $this->log('1-7-6-0 写入服务商分红信息: 完成');
                            //写入分红商家得信息11
                            if($order['order_source']==40){
                                $this->log('1-7-6-1 信息:');
                                $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                                $this->log('1-7-6-2 储值信息:',$CardSetting);
                                $this->setStoreAccounts(2,0,$order,$CardSetting,$periods_num);
                                $this->log('1-7-6-3 储值信息:结束');
                            }elseif($order['order_source']==50 || $order['order_source'] == 10 ){
                                $this->log('1-7-6-4 储值信息:结束');
                                $this->setStoreAccounts(1,0,$order,$setting,$periods_num);
                                $this->log('1-7-6-5 储值信息:结束');
                            }

                            $this->log('1-7-6-6 写入分红商家得信息: 完成');
                            //调用分账接口
                            $req=$Abonus->addReceiver();
                            $this->log('1-7-6-7 将服务商添加到 微信端分账接收方结束');
                            if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                                $this->log('1-7-6-8  微信端分账接收方结束');
                                sleep(60);
                                $reault=$Abonus->profitSharings($order);
                                $this->log('1-7-6-9  微信端分账');
                                if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                                    $this->log('1-7-7-0 系统分账结果',$reault);
                                    // return true;
                                    //将结束时间大于订单时间的人出局
                                    $this->setUserfinish($setting,$lastUser,$order);
                                    $this->log('1-7-7-1 系统分账结果');
                                }else{
                                    $this->log('1-7-7-2 系统分账失败结果',$reault);
                                    $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                                    $this->log('1-7-7-3 系统分账失败结果');
                                }
                                $this->log('1-7-7-4 分红结果: ', $reault);

                            }else{
                                $this->log('1-7-7-5 将服务商添加到分账接收方失败');
                            }
                        }else{
                            // 给系统、服务商、商户写入分账数据
                            //写入分红系统平台得信息
                            $this->log('1-7-7-6 写入分红系统平台得信息: 开始...');
                            $this->setSystemAccounts($order,$setting['periods_num']);
                            $this->log('1-7-7-7 写入分红系统平台得信息: 完成');

                            //写入服务商分红信息
                            $this->log('1-7-7-8 写入服务商分红信息: 开始...');
                            $this->setOperateCenterAccounts($order,$setting['periods_num']);
                            $this->log('1-7-7-9 写入服务商分红信息: 完成');
                            //如果开启了分红设置，并且支付金额大于设置的分红金额，满足条件，给所有人分
                            if($order['order_source']==40){
                                $this->log('1-7-8-0 订单信息:');
                                $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                                $this->log('1-7-8-1 储值卡信息:');
                                if ($setting['end_time']>=$order['pay_time']){
                                    $this->log('1-7-8-2 储值卡信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(2,0,$order,$CardSetting,$setting);//计算用户的分红金额
                                    $this->log('1-7-8-3 金额信息:',$userMoney);
                                    $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                    $this->log('1-7-8-4 信息:');
                                }else{
                                    $this->log('1-7-8-5 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(2,1,$order,$CardSetting,$setting);//计算用户的分红金额
                                    $this->log('1-7-8-6 金额信息:',$userMoney);
                                    $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                    $this->log('1-7-8-7 信息:');
                                }
                                $this->log('1-7-8-9 计算分红金额:',$userMoney);
                            }elseif($order['order_source']==50 || $order['order_source'] == 10){
                                $this->log('1-7-9-0 信息:');
                                if ($setting['end_time']>=$order['pay_time']) {
                                    $this->log('1-7-9-1 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(1,0,$order,0,$setting);//计算用户的分红金额
                                    $this->log('1-7-9-2 金额信息:',$userMoney);
                                    $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                    $this->log('1-7-9-3 信息:');
                                }else{
                                    $this->log('1-7-9-4 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(1,1,$order,0,$setting);//计算用户的分红金额
                                    $this->log('1-7-9-5 信息:');
                                    $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                    $this->log('1-7-9-6 信息:');
                                }
                                $this->log('1-7-9-7 计算分红金额:',$userMoney);
                            }

                            if($setting['end_time']<$order['pay_time']){
                                $this->log('1-7-9-8 不给自己分:开始');
                                /**只给前面的人分红，自己不参与分红**/
                                $this->getNoSelfBackAbonus($order,$setting,$userMoney);
                                $this->log('1-7-9-9 不给自己分:结束');
                            }else{
                                $this->log('1-8-0-0 给自己分:开始');
                                /**给前面的人分红，自己也参与分红**/
                                $this->getMultipleBackAbonus($order,$setting,$userMoney);
                                $this->log('1-8-0-1 给自己分:结束');
                            }

                        }
                    }else{
                        /***********当结束时间存在****************/
                        //当订单进入后，如果支付时间小于开始时间，或者支付时间小于结束时间，或者支付时间小于最后一步订单出局时间，或者开关未开启
                        if($setting['start_time']>$order['pay_time']  //支付时间小于开始时间
                            || $setting['end_time']<$order['pay_time'] //支付时间大于结束时间
                            && $setting['end_time']<$lastUser['finish_time']  //完结时间大于结束时间
                            && $lastUser['finish_time']<$order['pay_time'] //支付时间大于完结时间
                            || $setting['status']==2 ){
                            $this->log('2-7-5-6 订单存在: ');
                            /**只给商户和系统分红**/
                            //如果支付金额小于设置金额或者未开启分红，只给系统和商户分账
                            $periods_num=0;
                            //写入分红系统平台得信息
                            $this->log('2-7-5-7 写入分红系统平台得信息: 开始...');
                            $this->setSystemAccounts($order,$periods_num);
                            $this->log('2-7-5-8 写入分红系统平台得信息: 完成');

                            //写入服务商分红信息
                            $this->log('2-7-5-9 写入服务商分红信息: 开始...');
                            $this->setOperateCenterAccounts($order,$periods_num);
                            $this->log('2-7-6-0 写入服务商分红信息: 完成');
                            //写入分红商家得信息11
                            if($order['order_source']==40){
                                $this->log('2-7-6-1 信息:');
                                $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                                $this->log('2-7-6-2 储值信息:',$CardSetting);
                                $this->setStoreAccounts(2,0,$order,$CardSetting,$periods_num);
                                $this->log('2-7-6-3 储值信息:结束');
                            }elseif($order['order_source']==50 || $order['order_source'] == 10 ){
                                $this->log('2-7-6-4 储值信息:结束');
                                $this->setStoreAccounts(1,0,$order,$setting,$periods_num);
                                $this->log('2-7-6-5 储值信息:结束');
                            }

                            $this->log('2-7-6-6 写入分红商家得信息: 完成');
                            //调用分账接口
                            $req=$Abonus->addReceiver();
                            $this->log('2-7-6-7 将服务商添加到 微信端分账接收方结束');
                            if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                                $this->log('2-7-6-8  微信端分账接收方结束');
                                sleep(60);
                                $reault=$Abonus->profitSharings($order);
                                $this->log('2-7-6-9  微信端分账');
                                if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                                    $this->log('2-7-7-0 系统分账结果',$reault);
                                    // return true;
                                    //将结束时间大于订单时间的人出局
                                    $this->setUserfinish($setting,$lastUser,$order);
                                    $this->log('2-7-7-1 系统分账结果');
                                }else{
                                    $this->log('2-7-7-2 系统分账失败结果',$reault);
                                    $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                                    $this->log('2-7-7-3 系统分账失败结果');
                                }
                                $this->log('2-7-7-4 分红结果: ', $reault);

                            }else{
                                $this->log('2-7-7-5 将服务商添加到分账接收方失败');
                            }
                        }else{
                            // 给系统、服务商、商户写入分账数据
                            //写入分红系统平台得信息
                            $this->log('2-7-7-6 写入分红系统平台得信息: 开始...');
                            $this->setSystemAccounts($order,$setting['periods_num']);
                            $this->log('2-7-7-7 写入分红系统平台得信息: 完成');

                            //写入服务商分红信息
                            $this->log('2-7-7-8 写入服务商分红信息: 开始...');
                            $this->setOperateCenterAccounts($order,$setting['periods_num']);
                            $this->log('2-7-7-9 写入服务商分红信息: 完成');
                            //如果开启了分红设置，并且支付金额大于设置的分红金额，满足条件，给所有人分
                            if($order['order_source']==40){
                                $this->log('2-7-8-0 订单信息:');
                                $CardSetting=$this->getWxappCardSetting($order['card']['card_id'],$order['wxapp_id']);//获取本次分红设置
                                $this->log('2-7-8-1 储值卡信息:');
                                if ($setting['end_time']>=$order['pay_time']){
                                    $this->log('2-7-8-2 储值卡信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(2,0,$order,$CardSetting,$setting);//计算用户的分红金额
                                    $this->log('2-7-8-3 金额信息:',$userMoney);
                                    $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                    $this->log('2-7-8-4 信息:');
                                }else{
                                    $this->log('2-7-8-5 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(2,1,$order,$CardSetting,$setting);//计算用户的分红金额
                                    $this->log('2-7-8-6 金额信息:',$userMoney);
                                    $this->setStoreAccounts(2,$userMoney,$order,$CardSetting,$setting['periods_num']);
                                    $this->log('2-7-8-7 信息:');
                                }
                                $this->log('2-7-8-9 计算分红金额:',$userMoney);
                            }elseif($order['order_source']==50 || $order['order_source'] == 10){
                                $this->log('2-7-9-0 信息:');
                                if ($setting['end_time']>=$order['pay_time']) {
                                    $this->log('2-7-9-1 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(1,0,$order,0,$setting);//计算用户的分红金额
                                    $this->log('2-7-9-2 金额信息:',$userMoney);
                                    $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                    $this->log('2-7-9-3 信息:');
                                }else{
                                    $this->log('2-7-9-4 信息:');
                                    //计算每个人分红的金额，@type：1.消费、2.储值卡，@item:0.自己参与，1.自己不参与，@order：订单，$cardsetting:储值卡设置信息，@setting:分红设置信息
                                    $userMoney=$this->getUserMoney(1,1,$order,0,$setting);//计算用户的分红金额
                                    $this->log('2-7-9-5 信息:');
                                    $this->setStoreAccounts(1,$userMoney,$order,$setting,$setting['periods_num']);
                                    $this->log('2-7-9-6 信息:');
                                }
                                $this->log('2-7-9-7 计算分红金额:',$userMoney);
                            }

                            if($lastUser['finish_time']>$order['pay_time'] && $setting['end_time']<$order['pay_time']){
                                $this->log('2-7-9-8 不给自己分:开始');
                                /**只给前面的人分红，自己不参与分红**/
                                $this->getNoSelfBackAbonus($order,$setting,$userMoney);
                                $this->log('2-7-9-9 不给自己分:结束');
                            }else{
                                $this->log('2-8-0-0 给自己分:开始');
                                /**给前面的人分红，自己也参与分红**/
                                $this->getMultipleBackAbonus($order,$setting,$userMoney);
                                $this->log('2-8-0-1 给自己分:结束');
                            }

                        }

                    }

                }



            }catch(\Throwable $t){
                $err = [
                    'code' => $t->getCode(),
                    'line' => $t->getLine(),
                    'file' => $t->getFile(),
                    'msg' => $t->getMessage()
                ];
                $this->log('队列消费异常' . json_encode($err, JSON_UNESCAPED_UNICODE));
            }
        };
        $rmq->run($processMessage, 'userListData','userListDataLog','userListDataLog');
    }


    /**
     *  给首位用户退款->给系统分红->给前面的用户退款
     * @param $order
     * @param $setting
     * @param $userMoney
     * @return bool
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getMultipleBackAbonus($order,$setting,$userMoney){
        $this->log('1-8-0-2 用户退款逻辑开始...');
        $userList=collection(db('divide_receives')
            ->where(['wxapp_id'=>$order['wxapp_id'],'type'=>0,'periods_num'=>$setting['periods_num']])
            ->field('receives_id,type,order_no, times,balance,wxapp_id,payment,periods_num,user_id,account,top_limit,transaction_id,finish_time')
            ->order('create_time desc')
            ->select())->toArray();
        $this->log('1-8-0-3 查询用户信息: ', $userList);
        //调用分账接口
        $Abonus=new Abonus($order['wxapp_id']);
        if(count($userList)==0){
            /****************第一个人 start***********************/
            $this->log('1-8-0-4 单用户开始');

            if($setting['money']>$order['pay_price']){
                $this->log('1-8-0-5 支付金额小于设置金额');
                //如果实际支付金额小于设定金额,不给用户分，只给系统分
                $req=$Abonus->addReceiver();
                $this->log('1-8-0-6 将系统添加到分账方');
                if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                    $this->log('1-8-0-7 将系统添加到分账方成功');
                    //调用分账接口
                    sleep(30);
                    $this->log('1-8-0-8 系统分账开始');
                    $reault=$Abonus->profitSharings($order);
                    if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                        $this->log('1-8-0-9 系统分账结果',$reault);
                        //本人是第一个，不存在前面人
                        return true;
                    }else{
                        $this->log('1-8-1-0 系统分账失败结果',$reault);
                        $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                    }
                }else{
                    $this->log('1-8-1-1 将服务商添加到分账接收方失败');
                }
            }else{
                $this->log('1-8-1-2 支付金额大于或等于设置金额');
                //计算用户的分红上限
                $topLimit=bcmul(($setting['upline']/100),$order['pay_price'],2);
                $this->log('1-8-1-3 第一个用户上限金额',$topLimit);
                //如果分红上限小于本次分红金额，则本次分红金额为上限金额
                if($topLimit<=$userMoney){
                    $userMoney=$topLimit;
                    $this->log('1-8-1-4 第一个用户实际分的金额',$userMoney);
                }
                //如果实际支付金额大于或等于设定金额
                //直接给用户分
                $res=$this->getOneUserBackAbonus($order['wxapp_id'],$order['transaction_id'],$order['pay_price'],$userMoney);
                $this->log('1-8-1-5 用户退款结果',$res);
                if($res['return_code']=='SUCCESS' && $res['result_code']=='SUCCESS'){
                    //将用户分账信息写入主表
                    $red=$this->setUserBackAccounts($setting,$order,$userMoney,$setting['periods_num']);
                    $this->log('1-8-1-6 用户退款写入完成结果');
                    if(!empty($red)){
                        //将数据写入附表中,第一次写入，次数是1
                        $rea=$this->setReceivesUserAccounts(1,1,$red,$res['refund_id'],$userMoney,1,$order);
                        $this->log('1-8-1-7 用户退款写入附表完成结果');
                        if($rea==1){
                            //将用户设置为微股东
                            $this->setUserShareholderAccounts($order['user_id']);
                            $this->log('1-8-1-8 将用户设置为微股东结果');
                            //添加系统为分账方，给系统分账
                            $this->log('1-8-1-9 将系统添加到分账方开始');
                            $req=$Abonus->addReceiver();
                            if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                                $this->log('1-8-2-0 将系统添加到分账方成功');
                                //调用分账接口
                                sleep(30);
                                $reault=$Abonus->profitSharings($order);
                                $this->log('1-8-2-1 系统分账结果');
                                if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                                    //本人是第一个，不存在前面人
                                    return true;
                                }else{
                                    $this->log('1-8-2-2 系统分账失败');
                                    $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                                }
                            }else{
                                $this->log('1-8-2-3 将服务商添加到分账接收方失败');
                            }
                        }else{
                            $this->log('1-8-2-4 写入失败');
                        }
                    }else{
                        $this->log('1-8-2-5 写入失败');
                    }
                }else{
                    $this->log('1-8-2-6 写入失败');
                }
            }
            /****************第一个人 end***********************/
        }else{
            /****************多人 start***********************/
            $this->log('1-8-2-7 多用户开始');

            /****************支付金额小于分红金额 start***********************/
            //支付金额小于分红金额
            if($setting['money']>$order['pay_price']){
                $this->log('1-8-2-8  设置金额',$setting['money']);
                $this->log('1-8-2-9  支付金额',$order['pay_price']);
                if(intval($userMoney*100)<1){
                    $this->log('1-8-3-0  用户分红金额小于1分钱',$userMoney);
                    /**因为用户支付金额小于设置金额，且每个人分得的金额小于一分钱，只给系统分**/

                    //给系统品台分账
                    $this->log('1-8-3-1 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-8-3-2 将系统添加到分账方成功');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-8-3-3 系统分账开始');
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            //给系统分账结束后返回true
                            return true;

                        }else{
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-8-3-4 将服务商添加到分账接收方失败');
                    }

                }else{
                    /**因为用户支付金额小于设置金额，且每个人分得的金额大于等于一分钱，只给系统分和前面的人分**/
                    $this->log('1-8-3-5  用户分红金额大于等于1分钱',$userMoney);

                    //实际支付金额小于设置金额，不给支付人分账，给系统和前面的人分账
                    $this->log('1-8-3-6 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-8-3-7 将系统添加到分账方成功');
                        //调用分账接口
                        sleep(30);
                        $this->log('1-8-3-8 系统分账开始');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-8-3-9 系统分账结果',$reault);
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            //给之前的人退款
                            sleep(5);
                            $this->setRefundUsersBackAccounts($userList,$userMoney,$order,$setting);
                            $this->log('1-8-4-0 系统分账结果');
                        }else{
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-8-4-1 将服务商添加到分账接收方失败');
                    }
                }
                /****************支付金额小于分红金额 end***********************/
            }else{
                $this->log('1-8-4-2 多用户开始');


                //实际支付金额大于等于设置金额，给自己分账，也给前面的人分
                //如果分账金额小于1分钱，不给用户分
                if(intval($userMoney*100)<1){
                    /**因为用户支付金额大于等于设置金额，且每个人分得的金额小于一分钱，只给系统分，不给前面的人分，把用户写入分红队列**/
                    $this->log('1-8-4-3 多用户开始');

                    //将用户设置为微股东
                    $this->setUserShareholderAccounts($order['user_id']);
                    $this->log('1-8-4-4 将用户设置为微股东');
                    //实际支付金额小于设置金额，不给支付人分账，给系统和前面的人分账
                    $this->log('1-8-4-5 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    $this->log('1-8-4-6 将系统添加到分账方结果',$req);
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-8-4-7 将系统添加到分账方成功');
                        //调用分账接口
                        sleep(30);
                        $this->log('1-8-4-8 系统分账开始');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-8-4-9 系统分账结果',$reault);
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            $this->log('1-8-5-0 系统分账结果');
                            //给之前的人退款
                            return true;

                        }else{
                            $this->log('1-8-5-1 系统分账失败');
                            //分账失败
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-8-5-2 将服务商添加到分账接收方失败');
                    }
                }else{
                    $this->log('1-8-5-3 多用户开始');
                    /**因为用户支付金额大于等于设置金额，且每个人分得的金额大于等于一分钱，给系统分和前面的人分，把用户写入分红队列**/
                    //计算用户的分红上限
                    $topLimit=bcmul(($setting['upline']/100),$order['pay_price'],2);
                    $this->log('1-8-5-4 用户上限',$topLimit);
                    //如果分红上限小于本次分红金额，则本次分红金额为上限金额
                    if($topLimit<=$userMoney){
                        $userMoney=$topLimit;
                        $this->log('1-8-5-5 用户实际分红金额',$userMoney);
                    }

                    //用户分红金额大于1分钱，都参与分红
                    $res=$this->getOneUserBackAbonus($order['wxapp_id'],$order['transaction_id'],$order['pay_price'],$userMoney);
                    $this->log('1-8-5-6 用户退款',$res);
                    if($res['return_code']=='SUCCESS' && $res['result_code']=='SUCCESS'){
                        //将出账方写入数据库
                        $reaults=$this->setUserBackAccounts($setting,$order,$userMoney,$setting['periods_num']);
                        $this->log('1-8-5-7 用户写入分红队列');
                        if(!empty($reaults)){
                            //将数据写入附表中，第n次写入，次数n
                            $rea=$this->setReceivesUserAccounts(1,1,$reaults,$res['refund_id'],$userMoney,1,$order);
                            $this->log('1-8-5-8 用户写入分红队列附表');
                            if($rea==1){
                                //将用户设置为微股东
                                $this->setUserShareholderAccounts($order['user_id']);
                                $this->log('1-8-5-9 将用户设置为微股东');
                                //添加微信分账方
                                $this->log('1-8-6-0 将系统添加到分账方');
                                $req=$Abonus->addReceiver();
                                $this->log('1-8-6-1 将系统添加到分账方结果',$req);
                                if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                                    $this->log('1-8-6-2 将系统添加到分账方成功');
                                    sleep(30);
                                    $this->log('1-8-6-3 系统分账开始');
                                    $reault=$Abonus->profitSharings($order);
                                    $this->log('1-8-6-4 系统分账结果',$reault);
                                    if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                                        $this->log('1-8-6-5 用户分账');
                                        //统计实际参与分账人数,参与分账的用户分账的金额已返完的不参与分账
                                        sleep(5);
                                        $this->setRefundUsersBackAccounts($userList,$userMoney,$order,$setting);
                                        $this->log('1-8-6-6 用户分账结果');
                                    }else{
                                        $this->log('1-8-6-7 系统分账结果失败');
                                        $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);

                                    }
                                }else{
                                    $this->log('1-8-6-8 将服务商添加到分账接收方失败');
                                }
                            }else{
                                $this->log('1-8-6-9 写入附表失败');
                            }
                        }else{
                            $this->log('1-8-7-0 将支付人添加到接收方失败');
                        }
                    }else{
                        $this->log('1-8-7-1 支付人退款失败');
                    }
                }

            }

            /****************多人 end***********************/
        }
    }
    //不给自己分
    private function getNoSelfBackAbonus($order,$setting,$userMoney){
        $this->log('1-8-7-2 用户退款逻辑开始...');
        $userList=collection(db('divide_receives')
            ->where(['wxapp_id'=>$order['wxapp_id'],'type'=>0,'periods_num'=>$setting['periods_num']])
            ->field('receives_id,type,order_no, times,balance,wxapp_id,payment,periods_num,user_id,account,top_limit,transaction_id,finish_time')
            ->order('create_time desc')
            ->select())->toArray();
        $this->log('1-8-7-3 查询用户信息: ', $userList);
        //调用分账接口
        $Abonus=new Abonus($order['wxapp_id']);
        if(count($userList)==0){
            //如果是0的话，所有人都已出局，直接给系统分账
            $req=$Abonus->addReceiver();
            if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                $this->log('1-8-7-4 将系统添加到分账方成功');
                $reault=$Abonus->profitSharings($order);
                $this->log('1-8-7-5 系统分账开始');
                if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                    $this->log('1-8-7-6 系统分账结束');
                    //给系统分账结束后返回true
                    return true;
                }else{
                    $this->log('1-8-7-7 系统分账');
                    $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                }
            }else{
                $this->log('1-8-7-8 将服务商添加到分账接收方失败');
            }

        }else{
            /****************多人 start***********************/
            $this->log('1-8-7-9 多用户开始');
            /****************支付金额小于分红金额 start***********************/
            //支付金额小于分红金额
            if($setting['money']>$order['pay_price']){
                $this->log('1-8-8-0  设置金额',$setting['money']);
                $this->log('1-8-8-1  支付金额',$order['pay_price']);
                if(intval($userMoney*100)<1){
                    $this->log('1-8-8-2  用户分红金额小于1分钱',$userMoney);
                    /**因为用户支付金额小于设置金额，且每个人分得的金额小于一分钱，只给系统分**/
                    //给系统品台分账
                    $this->log('1-8-8-3 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-8-8-4 将系统添加到分账方成功');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-8-8-5 系统分账开始',$reault);
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            //给系统分账结束后返回true
                            return true;
                        }else{
                            $this->log('1-8-8-6 系统分账');
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-8-8-7 将服务商添加到分账接收方失败');
                    }

                }else{
                    /**因为用户支付金额小于设置金额，且每个人分得的金额大于等于一分钱，只给系统分和前面的人分**/
                    $this->log('1-8-8-9  用户分红金额大于等于1分钱',$userMoney);
                    //实际支付金额小于设置金额，不给支付人分账，给系统和前面的人分账
                    $this->log('1-8-9-0 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-8-9-1 将系统添加到分账方成功');
                        //调用分账接口
                        sleep(30);
                        $this->log('1-8-9-2 系统分账开始');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-8-9-3 系统分账结果',$reault);
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            $this->log('1-8-9-4 系统分账结果');
                            //给之前的人退款
                            sleep(5);
                            $this->setRefundUsersBackAccounts($userList,$userMoney,$order,$setting);
                        }else{
                            $this->log('1-8-9-5 系统分账结果');
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-8-9-6 将服务商添加到分账接收方失败');
                    }
                }
                /****************支付金额小于分红金额 end***********************/
            }else{
                $this->log('1-8-9-7 多用户开始');

                //实际支付金额大于等于设置金额，给自己分账，也给前面的人分
                //如果分账金额小于1分钱，不给用户分
                if(intval($userMoney*100)<1){
                    /**因为用户支付金额大于等于设置金额，且每个人分得的金额小于一分钱，只给系统分，不给前面的人分，把用户写入分红队列**/
                    $this->log('1-8-9-8 多用户开始');
                    //将用户设置为微股东
                    $this->setUserShareholderAccounts($order['user_id']);
                    $this->log('1-8-9-9 将用户设置为微股东');
                    //实际支付金额小于设置金额，不给支付人分账，给系统和前面的人分账
                    $this->log('1-9-0-0 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    $this->log('1-9-0-1 将系统添加到分账方结果',$req);
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-9-0-2 将系统添加到分账方成功');
                        //调用分账接口
                        sleep(30);
                        $this->log('1-9-0-3 系统分账开始');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-9-0-4 系统分账结果',$reault);
                        if($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            //不给之前的人退款，直接返回true
                            return true;
                        }else{
                            $this->log('1-9-0-5 系统分账失败');
                            //分账失败
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-9-0-6 将服务商添加到分账接收方失败');
                    }
                }else{
                    $this->log('1-9-0-7 多用户开始');
                    /**因为用户支付金额大于等于设置金额，且每个人分得的金额大于等于一分钱，给系统分和前面的人分**/
                    //用户分红金额大于1分钱，前面的用户都参与分红
                    //添加微信分账方
                    $this->log('1-9-0-8 将系统添加到分账方');
                    $req=$Abonus->addReceiver();
                    $this->log('1-9-0-9 将系统添加到分账方结果',$req);
                    if($req['return_code']=='SUCCESS' &&  $req['result_code']=='SUCCESS'){
                        $this->log('1-9-1-0 将系统添加到分账方成功');
                        sleep(30);
                        $this->log('1-9-1-1 系统分账开始');
                        $reault=$Abonus->profitSharings($order);
                        $this->log('1-9-1-2 系统分账结果',$reault);
                        if ($reault['return_code']=='SUCCESS' && $reault['result_code']=='SUCCESS'){
                            //统计实际参与分账人数,参与分账的用户分账的金额已返完的不参与分账
                            sleep(5);
                            $this->setRefundUsersBackAccounts($userList,$userMoney,$order,$setting);
                            $this->log('1-9-1-3 系统分账结果');
                        }else{
                            $this->log('1-9-1-4 系统分账结果失败');
                            $this->setSystemAbonus($order['order_no'],$reault['err_code_des']);
                        }
                    }else{
                        $this->log('1-9-1-5 将服务商添加到分账接收方失败');
                    }
                }
            }

            /****************多人 end***********************/

        }
    }
    /**
     *  分账未完成的时候
     * @param $type int 类型1.分账结果查询，2.分账完结结果
     * @param $order array 订单信息
     * @param $Abonus object 分账对象
     * @return bool
     */
    private function profitSharingQuery($type,$order, $Abonus){
        if($type==1){
            $result=$Abonus->query($order);
            if($result['return_code'] =='SUCCESS' && $result['result_code']== 'SUCCESS'){
                return true;
            }elseif($result['return_code'] =='SUCCESS'  &&  ($result['status'] =='PROCESSING' ||  $result['status'] =='ACCEPTED')){
                sleep(1);
                $Abonus->profitSharingQuery($order,$Abonus);
            }elseif($result['return_code'] =='SUCCESS'  &&  $result['status'] =='FINISHED'){
                return  true;

            }elseif($result['return_code'] =='SUCCESS'  &&  $result['status'] =='CLOSED'){
                $this->setSystemAbonus($order['order_no'],$result['err_code_des']);
            }
        }else{
            $result=$Abonus->query($order);
            if($result['return_code'] =='SUCCESS' && $result['result_code']== 'SUCCESS'){
                return true;
            }elseif($result['return_code'] =='SUCCESS'  &&  ($result['status'] =='PROCESSING' ||  $result['status'] =='ACCEPTED')){
                sleep(1);
                $Abonus->profitSharingQuery($order,$Abonus);
            }elseif($result['return_code'] =='SUCCESS'  &&  $result['status'] =='FINISHED'){
                return  true;

            }elseif($result['return_code'] =='SUCCESS'  &&  $result['status'] =='CLOSED'){
                $this->setSystemAbonus($order['order_no'],$result['err_code_des']);
            }
        }

    }

    /**
     * 退还之前的用户分红
     * @param $userList
     * @param $userMoney
     * @param $order
     * @param $setting
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function setRefundUsersBackAccounts($userList,$userMoney,$order,$setting){
        $this->log('1-9-1-6 接入分红用户数据',$userList);
        $this->log('1-9-1-7 接入用户分红金额',$userMoney);
        $this->log('1-9-1-8 接入分红订单数据',$order);
        $this->log('1-9-1-9 接入商家分红设置',$setting);
        foreach ($userList as $key=>$item){
            if(empty($item['finish_time']) || $item['finish_time']==0){
                //如果出局时间大于当前时间，用户继续分红
                if($item['balance']<$userMoney){
                    $this->log('1-9-3-1 剩余余额小于分红金额',$item['balance']);
                    $this->log('1-9-3-2 剩余余额小于分红金额',$userMoney);
                    //用户余额小于能分到的金额
                    if($item['times']>=46){
                        $this->log('1-9-3-3 剩余次数大于46次',$item['times']);
                        //退款次数大于等于46次
                        //将剩余未退的金额以赏金的形式返还给用户
                        $reas=$this->setUserDealer($item['balance'],$item);
                        $this->log('1-9-3-4 将剩余未退的金额以赏金的形式返还给用户');
                        if($reas==1){
                            //如果转成还是赏金成功
                            //修改主表数据，用户剩余未分金额清空@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                            $this->setUserUpdata(2,$item['receives_id'],$item['balance']);
                            $this->log('1-9-3-5 修改主表数据，用户剩余未分金额清空');
                            //经数据写入附表
                            $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$item['balance'],1,$order);
                            $this->log('1-9-3-6 经数据写入附表');
                            //将退完款的人出局,也退出微股东
                            $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                            $this->log('1-9-3-7 将退完款的人出局');
                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,'写入数据失败',$item['balance'],$item['periods_num']);
                            $this->log('1-9-3-8 用户退款');
                        }
                    }else{
                        //退款次数小于46次
                        // 退换剩余的分红实际金额直接已退款的形式退回给用户
                        $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$item['balance']);
                        $this->log('1-9-3-9 用户退款结果',$reas);
                        if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                            //修改主表数据，剩余余额清空
                            $this->setUserUpdata(1,$item['receives_id'],$item['balance']);
                            $this->log('1-9-4-0 修改主表数据，剩余余额清空');
                            //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                            $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$item['balance'],1,$order);
                            $this->log('1-9-4-1 经数据写入附表');
                            //将退完款的人出局
                            $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                            $this->log('1-9-4-2 将退完款的人出局');
                            //将退完款的人退出微股东

                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,$reas['err_code_des'],$item['balance'],$item['periods_num']);
                            $this->log('1-9-4-3 用户退款失败');
                        }
                    }


                }elseif($item['balance']==$userMoney){
                    $this->log('1-9-4-4 接入商家分红设置',$setting);
                    //用户剩余余额等于
                    if($item['times']>=46 ){
                        $this->log('1-9-4-5 剩余次数大于46次',$item['times']);
                        //将剩余的资金退还到用户赏金账户
                        $reas=$this->setUserDealer($userMoney,$item);
                        $this->log('1-9-4-6 将剩余的资金退还到用户赏金账户');
                        if($reas==1){
                            //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                            $this->setUserUpdata(2,$item['receives_id'],$item['balance']);
                            $this->log('1-9-4-7 修改主表数据');
                            //经数据写入附表
                            $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$userMoney,1,$order);
                            $this->log('1-9-4-8 经数据写入附表');
                            //将退完款的人出局
                            $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                            $this->log('1-9-4-9 将退完款的人出局');
                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,'写入数据失败',$userMoney,$item['periods_num']);
                            $this->log('1-9-5-0 用户退款失败表');
                        }


                    }else{
                        $this->log('1-9-5-1 剩余次数小于46次',$item['times']);
                        // 退换剩余的分红实际金额,以退款的形式
                        $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$userMoney);
                        $this->log('1-9-5-2 退换剩余的分红实际金额,以退款的形式');
                        if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                            //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                            $this->setUserUpdata(1,$item['receives_id'],$userMoney);
                            $this->log('1-9-5-3 修改主表数据');
                            //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                            $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$userMoney,1,$order);
                            $this->log('1-9-5-4 经数据写入附表');
                            //将退完款的人出局
                            $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                            $this->log('1-9-5-5 将退完款的人出局');
                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,$reas['err_code_des'],$userMoney,$item['periods_num']);
                            $this->log('1-9-5-6 用户退款失败');

                        }

                    }
                }elseif($item['balance']>$userMoney){
                    $this->log('1-9-5-7 接入商家分红设置',$setting);
                    $this->log('1-9-5-8 接入商家分红设置',$userMoney);
                    //用户退款次数大于46次的时候
                    if($item['times']>=46){
                        $this->log('1-9-5-9 剩余次数大于46次',$item['times']);
                        //将用户本次的金额以赏金的形式退给用户
                        $reas=$this->setUserDealer($userMoney,$item);
                        $this->log('1-9-6-0 将用户本次的金额以赏金的形式退给用户');
                        if($reas==1){
                            //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                            $this->setUserUpdata(2,$item['receives_id'],$userMoney);
                            $this->log('1-9-6-1 修改主表数据');
                            //经数据写入附表
                            $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$userMoney,1,$order);
                            $this->log('1-9-6-2 经数据写入附表');
                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,'写入数据失败',$userMoney,$item['periods_num']);
                            $this->log('1-9-6-3 用户退款失败表');
                        }

                    }else{
                        // 退换剩余的分红实际金额以退款的形式返还
                        $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$userMoney);
                        $this->log('1-9-6-4 退换剩余的分红实际金额以退款的形式返还结果',$reas);
                        if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                            //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                            $this->setUserUpdata(1,$item['receives_id'],$userMoney);
                            $this->log('1-9-6-5 修改主表数据');
                            //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                            $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$userMoney,1,$order);
                            $this->log('1-9-6-6 经数据写入附表');
                        }else{
                            //用户退款失败表
                            $this->setUserRefund($order,$setting,$reas['err_code_des'],$userMoney,$item['periods_num']);
                            $this->log('1-9-6-7 用户退款失败');
                        }
                    }
                }
            }else{
                if($item['finish_time']<$order['pay_time']){
                    //如果出局时间小于当前时间，用户不继续分红,剩余未返完的转成零钱
                    // 退换剩余的分红实际金额,以零钱的形式返还
                    $reas= $this->setUserBlance($item['balance'],$item);
                    $this->log('2-9-2-0 退换剩余的分红实际金额,以退款的形式');
                    if($reas==1){
                        //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                        $this->setUserUpdata(3,$item['receives_id'],$item['balance']);
                        $this->log('2-9-2-1 修改主表数据');
                        //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金,3.零钱），主表id，退款等单号，实际退款金额，退款状态
                        $this->setReceivesUserAccounts(2,3,$item['receives_id'],0,$item['balance'],1,$order);
                        $this->log('2-9-2-2 经数据写入附表');

                        //将退完款的人出局
                        $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                        $this->log('2-9-2-3 将退完款的人出局');
                    }else{
                        //用户退款失败表
                        $this->setUserRefund($order,$setting,0,$item['balance'],$item['periods_num']);
                        $this->log('2-9-2-4 用户退款失败');
                    }
                }else{
                    //如果出局时间大于当前时间，用户继续分红
                    if($item['balance']<$userMoney){
                        $this->log('2-9-3-1 剩余余额小于分红金额',$item['balance']);
                        $this->log('2-9-3-2 剩余余额小于分红金额',$userMoney);
                        //用户余额小于能分到的金额
                        if($item['times']>=46){
                            $this->log('2-9-3-3 剩余次数大于46次',$item['times']);
                            //退款次数大于等于46次
                            //将剩余未退的金额以赏金的形式返还给用户
                            $reas=$this->setUserDealer($item['balance'],$item);
                            $this->log('2-9-3-4 将剩余未退的金额以赏金的形式返还给用户');
                            if($reas==1){
                                //如果转成还是赏金成功
                                //修改主表数据，用户剩余未分金额清空@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                                $this->setUserUpdata(2,$item['receives_id'],$item['balance']);
                                $this->log('2-9-3-5 修改主表数据，用户剩余未分金额清空');
                                //经数据写入附表
                                $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$item['balance'],1,$order);
                                $this->log('2-9-3-6 经数据写入附表');
                                //将退完款的人出局,也退出微股东
                                $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                                $this->log('2-9-3-7 将退完款的人出局');
                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,'写入数据失败',$item['balance'],$item['periods_num']);
                                $this->log('2-9-3-8 用户退款');
                            }
                        }else{
                            //退款次数小于46次
                            // 退换剩余的分红实际金额直接已退款的形式退回给用户
                            $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$item['balance']);
                            $this->log('2-9-3-9 用户退款结果',$reas);
                            if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                                //修改主表数据，剩余余额清空
                                $this->setUserUpdata(1,$item['receives_id'],$item['balance']);
                                $this->log('2-9-4-0 修改主表数据，剩余余额清空');
                                //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                                $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$item['balance'],1,$order);
                                $this->log('2-9-4-1 经数据写入附表');
                                //将退完款的人出局
                                $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                                $this->log('2-9-4-2 将退完款的人出局');
                                //将退完款的人退出微股东


                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,$reas['err_code_des'],$item['balance'],$item['periods_num']);
                                $this->log('2-9-4-3 用户退款失败');
                            }
                        }
                    }elseif($item['balance']==$userMoney){
                        $this->log('2-9-4-4 接入商家分红设置',$setting);
                        //用户剩余余额等于
                        if($item['times']>=46 ){
                            $this->log('2-9-4-5 剩余次数大于46次',$item['times']);
                            //将剩余的资金退还到用户赏金账户
                            $reas=$this->setUserDealer($userMoney,$item);
                            $this->log('2-9-4-6 将剩余的资金退还到用户赏金账户');
                            if($reas==1){
                                //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                                $this->setUserUpdata(2,$item['receives_id'],$item['balance']);
                                $this->log('2-9-4-7 修改主表数据');
                                //经数据写入附表
                                $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$userMoney,1,$order);
                                $this->log('2-9-4-8 经数据写入附表');
                                //将退完款的人出局
                                $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                                $this->log('2-9-4-9 将退完款的人出局');
                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,'写入数据失败',$userMoney,$item['periods_num']);
                                $this->log('2-9-5-0 用户退款失败表');
                            }

                        }else{
                            $this->log('2-9-5-1 剩余次数小于46次',$item['times']);
                            // 退换剩余的分红实际金额,以退款的形式
                            $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$userMoney);
                            $this->log('2-9-5-2 退换剩余的分红实际金额,以退款的形式');
                            if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                                //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                                $this->setUserUpdata(1,$item['receives_id'],$userMoney);
                                $this->log('2-9-5-3 修改主表数据');
                                //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                                $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$userMoney,1,$order);
                                $this->log('2-9-5-4 经数据写入附表');
                                //将退完款的人出局
                                $this->setUserOutAccounts($item['receives_id'],$item['user_id']);
                                $this->log('2-9-5-5 将退完款的人出局');
                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,$reas['err_code_des'],$userMoney,$item['periods_num']);
                                $this->log('2-9-5-6 用户退款失败');

                            }

                        }
                    }elseif($item['balance']>$userMoney){
                        $this->log('2-9-5-7 接入商家分红设置',$setting);
                        $this->log('2-9-5-8 接入商家分红设置',$userMoney);
                        //用户退款次数大于46次的时候
                        if($item['times']>=46){
                            $this->log('2-9-5-9 剩余次数大于46次',$item['times']);
                            //将用户本次的金额以赏金的形式退给用户
                            $reas=$this->setUserDealer($userMoney,$item);
                            $this->log('2-9-6-0 将用户本次的金额以赏金的形式退给用户');
                            if($reas==1){
                                //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                                $this->setUserUpdata(2,$item['receives_id'],$userMoney);
                                $this->log('2-9-6-1 修改主表数据');
                                //经数据写入附表
                                $this->setReceivesUserAccounts(2,2,$item['receives_id'],0,$userMoney,1,$order);
                                $this->log('2-9-6-2 经数据写入附表');
                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,'写入数据失败',$userMoney,$item['periods_num']);
                                $this->log('2-9-6-3 用户退款失败表');
                            }
                        }else{
                            // 退换剩余的分红实际金额以退款的形式返还
                            $reas= $this->getOneUserBackAbonus($item['wxapp_id'],$item['transaction_id'],$item['payment'],$userMoney);
                            $this->log('2-9-6-4 退换剩余的分红实际金额以退款的形式返还结果',$reas);
                            if($reas['return_code']=='SUCCESS' && $reas['result_code']=='SUCCESS'){
                                //修改主表数据@type(1.微信退款，2.赏金退款，3.零钱退款)，主表id，余额
                                $this->setUserUpdata(1,$item['receives_id'],$userMoney);
                                $this->log('2-9-6-5 修改主表数据');
                                //经数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金），主表id，退款等单号，实际退款金额，退款状态
                                $this->setReceivesUserAccounts(2,1,$item['receives_id'],$reas['refund_id'],$userMoney,1,$order);
                                $this->log('2-9-6-6 经数据写入附表');
                            }else{
                                //用户退款失败表
                                $this->setUserRefund($order,$setting,$reas['err_code_des'],$userMoney,$item['periods_num']);
                                $this->log('2-9-6-7 用户退款失败');
                            }
                        }

                    }
                }
            }

        }
    }


    /**
     *  将系统分红写入数据表
     * @param $periods_num string 分红期号
     * @param $order array 订单信息
     */
    private function setSystemAccounts($order,$periods_num){

        //获取系统服务商信息
        $systemConfig=BaseSetting::getItem('wechat');
        $system['account']            =$systemConfig['mch_id'];//服务商商户id
        $system['order_no']           =$order['order_no'];//订单号
        $system['wxapp_id']           =$order['wxapp_id'];//微信小程序内部编号
        $system['abonus']             =bcmul($order['pay_price'],0.01,2);//分账可得金额(单位/分)
        $system['amount']             =bcmul($system['abonus'],0.2,4);//分红金额(单位/分)
        $system['description']        ='分账给系统服务商';
        $system['payment']            =$order['pay_price'];//实际支付总金额(单位/分)
        $system['transaction_id']     =$order['transaction_id'];//微信内部订单
        $system['status']             =0;//结算状态 0待分账 1已分账 2分账失败
        $system['create_time']        =time();//写入时间
        $system['periods_num']        =$periods_num;//期号
        return db('divide_system')->insert($system);
    }

    /**
     * @param $order array 订单信息
     * @param $periods_num  string   分红期号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setOperateCenterAccounts($order,$periods_num){
        //获取服务商的id
        $agentId=db('wxapp')->where(['wxapp_id'=>$order['wxapp_id']])->value('agent_id');

        if ($agentId!==0){
            $agentList=collection(db('agent')->where(['is_recycle'=>0,'status'=>1,'is_delete'=>0])->order('agent_id desc')->select())->toArray();//合伙人层级
            if (!empty($agentList)){
                $tree =Services::instance();
                $tree->init($agentList, 'recommend_id');
                $agentData=$tree->getParents($agentId,true);
                $agentCount=count($agentData);

                $agentDividendsDataArray=[];
                if($agentCount==1){
                    $agentDividendsDataArray['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray['type']          = 1;
                    $agentDividendsDataArray['agent_id']      = $agentData[0]['agent_id'];
                    // $agentDividendsDataArray['proportion']    = $agentData[0]['service_charge'];
                    $agentDividendsDataArray['amount']        = bcmul(($agentData[0]['service_charge']/100),($order['pay_price']*0.01),4);
                    // $agentDividendsDataArray['description']   ='分账给品牌商';
                    //  $agentDividendsDataArray['trade']         = $trade;//分账单号，小程序号+期号+时间
                    $agentDividendsDataArray['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                    $agentDividendsDataArray['order_no']      = $order['order_no'];//订单号
                    $agentDividendsDataArray['payment']       = $order['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray['transaction_id']= $order['transaction_id'];
                    $agentDividendsDataArray['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray['periods_num']   = $periods_num;//写入时间（支付时间）
                    db('divide_service')->insert($agentDividendsDataArray);
                }elseif ($agentCount==2){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['amount']        = bcmul((($agentData[0]['service_charge']-$agentData[1]['service_charge'])/100),bcmul($order['pay_price'],0.01,4),4);
                    $agentDividendsDataArray[0]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = $order['order_no'];//订单号
                    $agentDividendsDataArray[0]['payment']       = $order['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= $order['transaction_id'];
                    $agentDividendsDataArray[0]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['periods_num']   = $periods_num;//写入时间（支付时间）
                    if($agentData[1]['type']==1){
                        //分账给运营商
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'] ? $agentData[1]['company_name'] : $agentData[1]['real_name'];
                        $agentDividendsDataArray[1]['type']          = 2;
                        $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['amount']        = bcmul(($agentData[1]['service_charge']/100),bcmul($order['pay_price'],0.01,4),4);
                        $agentDividendsDataArray[1]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = $order['order_no'];//订单号
                        $agentDividendsDataArray[1]['payment']       = $order['pay_price'];//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= $order['transaction_id'];
                        $agentDividendsDataArray[1]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）
                    }elseif ($agentData[1]['type']==2){
                        //分账给合伙人
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['real_name'];
                        $agentDividendsDataArray[1]['type']          =3;
                        $agentDividendsDataArray[1]['agent_id']      =$agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['amount']        =bcmul(($agentData[1]['service_charge']/100),bcmul($order['pay_price'],0.01,4),4);
                        $agentDividendsDataArray[1]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = $order['order_no'];//订单号
                        $agentDividendsDataArray[1]['payment']       = $order['pay_price'];//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= $order['transaction_id'];
                        $agentDividendsDataArray[1]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）
                    }
                    db('divide_service')->insertAll($agentDividendsDataArray);

                }elseif($agentCount==3){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['amount']        = bcmul((($agentData[0]['service_charge']-$agentData[1]['service_charge'])/100),bcmul($order['pay_price'],0.01,4),4);
                    $agentDividendsDataArray[0]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = $order['order_no'];//订单号
                    $agentDividendsDataArray[0]['payment']       = $order['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= $order['transaction_id'];
                    $agentDividendsDataArray[0]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['periods_num']   = $periods_num;//写入时间（支付时间）

                    $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'] ? $agentData[1]['company_name'] : $agentData[1]['real_name'];
                    $agentDividendsDataArray[1]['type']          = 2;
                    $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                    $agentDividendsDataArray[1]['amount']        = bcmul((($agentData[1]['service_charge']-$agentData[2]['service_charge'])/100),bcmul($order['pay_price'],0.01,4),4);
                    $agentDividendsDataArray[1]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                    $agentDividendsDataArray[1]['order_no']      = $order['order_no'];//订单号
                    $agentDividendsDataArray[1]['payment']       = $order['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[1]['transaction_id']= $order['transaction_id'];
                    $agentDividendsDataArray[1]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[1]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[1]['periods_num']   = $periods_num;//写入时间（支付时间）


                    $agentDividendsDataArray[2]['name']          = $agentData[2]['real_name'];
                    $agentDividendsDataArray[2]['type']          = 3;
                    $agentDividendsDataArray[2]['agent_id']      = $agentData[2]['agent_id'];
                    $agentDividendsDataArray[2]['amount']        = bcmul(($agentData[2]['service_charge']/100),bcmul($order['pay_price'],0.01,4),4);
                    $agentDividendsDataArray[2]['abonus']        = bcmul($order['pay_price'],0.01,2);//参与分账金额
                    $agentDividendsDataArray[2]['order_no']      = $order['order_no'];//订单号
                    $agentDividendsDataArray[2]['payment']       = $order['pay_price'];//订单实际支付金额
                    $agentDividendsDataArray[2]['transaction_id']= $order['transaction_id'];
                    $agentDividendsDataArray[2]['wxapp_id']      = $order['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[2]['status']        = 0;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[2]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[2]['periods_num']   = $periods_num;//写入时间（支付时间）
                    db('divide_service')->insertAll($agentDividendsDataArray);
                }

            }
        }


    }

    /**
     *   将商户的分红金额入库
     * @param $type  int 类型 1.消费，2.储值
     * @param $money  float|int 用户分红金额
     * @param $order  array 订单信息
     * @param $setting array 分红信息
     * @param $periods_num int 分红期号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setStoreAccounts($type,$money,$order,$setting,$periods_num){

        $storeConfig=db('wxapp')->where('wxapp_id',$order['wxapp_id'])->find();
        $store['account']            =$storeConfig['mchid'];//服务商商户id
        $store['order_no']           =$order['order_no'];//订单号
        $store['wxapp_id']           =$order['wxapp_id'];//微信小程序内部编号
        if(($money*100)<1) {
            $store['amount'] = bcsub($order['pay_price'], bcmul($order['pay_price'], 0.01,2),2);
        }else{
            if($type==1){
                //消费分红
                $store['amount']     =bcmul($order['pay_price'],(1-$setting['rewardpercent']/100),2);
            }elseif ($type==2){
                //储值分红
                $store['amount']     =bcmul($order['pay_price'],(1-$setting['bonus_percent']/100),2);
            }

        }
        $store['agent_id']           = $storeConfig['agent_id'];
        $store['payment']            =$order['pay_price'];//实际支付总金额(单位/分)
        $store['transaction_id']     =$order['transaction_id'];//微信内部订单
        $store['status']             =0;//结算状态 0待分账 1已分账 2分账失败
        $store['create_time']        =time();//写入时间
        $store['periods_num']        =$periods_num;//期号
        db('divide_store')->insert($store);
    }




    /**
     * 将退款用户写入数据库
     * @param $type
     * @param $trade
     * @param $userMoney
     * @param $order
     * @param $periodsNum
     * @param $setting
     */
    private function setUserBackAccounts($setting,$order,$userMoney,$periodsNum){
        $userListData['user_id']         = $order['user_id'] ;
        $userListData['account']         = $this->getUserOpenId($order['user_id'],$order['wxapp_id']) ;
        $userListData['order_no']        = $order['order_no'] ;//订单号
        $userListData['wxapp_id']        = $order['wxapp_id'];//微信小程序id
        $userListData['payment']         = $order['pay_price'] ;//订单支付金额
        $userListData['periods_num']     = $periodsNum ;//活动期号
        $userListData['transaction_id']  = $order['transaction_id'] ;//订单号
        $userListData['top_limit']       = bcmul(($setting['upline']/100),$order['pay_price'],2);//用户分红上限
        if(intval($userMoney*100)<1){
            $userListData['balance']     = $userListData['top_limit'];//用户剩余分红金额
            $userListData['total_abonus']= 0;//用户累计分红金额，小于1分钱的时候，用户不参与分红，但是要写入分红队列
            $userListData['times']       = 0;//参与分红的次数，，小于1分钱的时候，用户分红次数是0，但是要写入分红队列
            $userListData['refund_money']= 0;//用户首次退款的时候退款金额
        }else{
            $userListData['balance']     = bcsub($userListData['top_limit'],$userMoney,2);//用户剩余分红金额
            $userListData['total_abonus']= $userMoney;////用户累计分红金额
            $userListData['times']       = 1;//参与分红的次数
            $userListData['refund_money']= $userMoney;//用户首次退款的时候退款金额
        }
        if ($userMoney==$userListData['top_limit']){
            $userListData['type']            = 1;//是否参与分账，0，参与，1.不参与
            $userListData['finish_time']     = time();
        }else{
            $userListData['type']            = 0;//是否参与分账，0，参与，1.不参与
            $userListData['finish_time']     = time()+($setting['term']*24*60*60);

        }
        $userListData['create_time']     = time();//写入时间（支付时间）
        $userListData['update_time']     = time();//写入时间（支付时间）

        return db('divide_receives')->insertGetId($userListData);
    }

    //将查询出来的最后一笔订单出局
    private function setUserfinish($setting,$lastUser,$order){

        //将剩余的资金退还到用户零钱账户
        $reas=$this->setUserBlance($lastUser['balance'],$lastUser);
        if($reas==1){
            //修改主表数据
            $this->setUserUpdata(3,$lastUser['receives_id'],$lastUser['balance']);

            //将数据写入附表,（1.第一次，2是多次），（1是现金,2是赏金,3.零钱），主表id，退款等单号，实际退款金额，退款状态
            $this->setReceivesUserAccounts(2,3,$lastUser['receives_id'],0,$lastUser['balance'],1,$order);

            //将退完款的人出局
            $this->setUserOutAccounts($lastUser['receives_id'],$lastUser['user_id']);

        }else{
            //用户退款失败表
            $this->setUserRefund($order,$setting,'写入数据失败',$lastUser['balance'],$lastUser['periods_num']);

        }
    }

    /**
     *  修改主表数据
     * @param $receivesId
     * @param $userMoney
     * @param $type 1.退款分红，2.赏金分红，3.零钱分红
     * @return int|string
     */
    private function setUserUpdata($type,$receivesId,$userMoney){

        if($type==1){
            return db('divide_receives')->where('receives_id',$receivesId)->setField(['balance'=>Db::raw('balance -'.$userMoney),'total_abonus'=>Db::raw('total_abonus +'.$userMoney),'refund_money'=>Db::raw('refund_money +'.$userMoney),'times'=>Db::raw('times + 1')]);
        }elseif ($type==2){
            return db('divide_receives')->where('receives_id',$receivesId)->setField(['balance'=>Db::raw('balance -'.$userMoney),'total_abonus'=>Db::raw('total_abonus +'.$userMoney),'reward_money'=>Db::raw('reward_money +'.$userMoney),'times'=>Db::raw('times + 1')]);
        }else{
            return db('divide_receives')->where('receives_id',$receivesId)->setField(['balance'=>Db::raw('balance -'.$userMoney),'total_abonus'=>Db::raw('total_abonus +'.$userMoney),'small_change'=>Db::raw('small_change +'.$userMoney),'times'=>Db::raw('times + 1')]);
        }



    }
    /**
     * 将每次的流水写入记录
     * @param $type int 第几次写入
     * @param $refund_type int 退款类型 1.现金 2.赏金 3.零钱
     * @param $receivesId  int 主表id
     * @param $refundId   int   退款订单id
     * @param $userMoney  float 用户退款金额
     * @param $status    int  是否成功
     * @param $times    int  次数
     * @return int|string
     */
    private function setReceivesUserAccounts($type, $refund_type, $receivesId, $refundId, $userMoney, $status, $order){
        //第一次写入记录
        if ($type==1){
            $userListData['receives_id']     = $receivesId;//主表id
            $userListData['extend']=json_encode([[
                'type' =>$refund_type,//退款类型 1.微信现金退款 2.赏金退款 3.零钱退款
                'refund_id'=>$refundId, //微信内部退款订单号
                'refund_fee'=>$userMoney,//退款金额
                'money'=>$order['pay_price'],//本次订单支付金额
                'order_no'=>$order['order_no'],//产生退款的订单编号
                'status'=>$status,    //退款状态 1.退款成功
                'times' =>1,//第几次退款
                'time' =>time()
            ]]);
            $userListData['create_time']     = time();//写入时间（支付时间）
            return db('divide_receives_user')->insert($userListData);
        }else{
            $extend[]=[
                'type' =>$refund_type,//退款类型 1.微信现金退款 2.赏金退款 3.零钱退款
                'refund_id'=>$refundId, //微信内部退款订单号
                'refund_fee'=>$userMoney,//退款金额
                'money'=>$order['pay_price'],//本次订单支付金额
                'order_no'=>$order['order_no'],//产生退款的订单编号
                'status'=>$status,    //退款状态 1.退款成功
                // 'times' => $times,//第几次退款

                'time' =>time()
            ];
            $extends=db('divide_receives_user')->where('receives_id',$receivesId)->value('extend');
            if($extends){
                $data = json_decode($extends, true);
                //最后一个数组
                $lastData=end($data);
                if(!isset($lastData['times'])){
                    $extend[0]['times']=1;
                }else{
                    $extend[0]['times']=$lastData['times']+1;
                }
                $json =array_merge($data,$extend);
                $res = json_encode($json );
                return db('divide_receives_user')->where('receives_id',$receivesId)->setField('extend',$res);
            }else{
                $userListData['receives_id']     = $receivesId;//主表id
                $userListData['extend']=json_encode([[
                    'type' =>$refund_type,//退款类型 1.微信现金退款 2.赏金退款 3.零钱退款
                    'refund_id'=>$refundId, //微信内部退款订单号
                    'refund_fee'=>$userMoney,//退款金额
                    'money'=>$order['pay_price'],//本次订单支付金额
                    'order_no'=>$order['order_no'],//产生退款的订单编号
                    'status'=>$status,    //退款状态 1.退款成功
                    'times' =>1,//第几次退款
                    'time' =>time()]]);

                $userListData['create_time']     = time();//写入时间（支付时间）
                return db('divide_receives_user')->insert($userListData);
            }
        }
    }

    /**
     * 用户退款失败
     * @param $order
     * @param $setting
     * @param $res
     * @param $trade
     * @param $userMoney
     * @param $periodsNum
     * @return int|string
     */
    private  function setUserRefund($order,$setting,$res,$userMoney,$periodsNum){
        $userListData['user_id']         = $order['user_id'] ;
        $userListData['account']         = $this->getUserOpenId($order['user_id'],$order['wxapp_id']) ;
        $userListData['order_no']        = $order['order_no'] ;//订单号
        $userListData['wxapp_id']        = $order['wxapp_id'];//微信小程序id
        $userListData['amount']          = $userMoney;
        $userListData['payment']         = $order['pay_price'] ;//订单支付金额
        $userListData['periods_num']     = $periodsNum ;//活动期号
        $userListData['transaction_id']  = $order['transaction_id'] ;//订单号
        $userListData['top_limit']       = bcmul(($setting['upline']/100),$order['pay_price'],2);//用户分红上限
        $userListData['type']            = 0;//是否参与分账，0，参与，1.不参与
        $userListData['status']          = 2;//用户退款，0、待分账，1.已分账，2.分账失败
        $userListData['fail_reason']     = $res;//是否参与分账，0，参与，1.不参与
        $userListData['create_time']     = time();//写入时间（支付时间）
        $userListData['update_time']     = time();//写入时间（支付时间）
        return db('divide_refund')->insert($userListData);
    }


    /**
     * 分账失败
     * @param $orderNo
     * @param $reason
     */
    private function setSystemAbonus($orderNo,$reason){
        db('divide_system')->where('order_no',$orderNo)->setField(['status'=>2,'fail_reason'=>$reason]);
        db('divide_store')->where('order_no',$orderNo)->setField(['status'=>2,'fail_reason'=>$reason]);
        db('divide_service')->where('order_no',$orderNo)->setField(['status'=>2,'fail_reason'=>$reason]);
    }

    /**
     *  将参与分红的会员转化成为微股东
     * @param $userId
     */
    private function setUserShareholderAccounts($userId){
        return  db('user')->where('user_id',$userId)->setField('shareholder',1);
    }

    /**
     * 将退款完账的订单出局
     * @param $receivesId
     * @param $userId
     * @return int|string
     */
    private function setUserOutAccounts($receivesId,$userId){
        return  db('divide_receives')->where(['receives_id'=>$receivesId,'user_id'=>$userId])->setField(['type'=>1]);
    }

    /**
     *  将出局的人也退出微股东
     * @param $userId
     * @return int|string
     */
    private function noUserShareholderAccounts($userId){
        return  db('user')->where('user_id',$userId)->setField('shareholder',0);
    }


    /**
     * 参与分红代言人可以分到的钱
     * @param $type int 分红类型 1.消费分红，2.储值分红
     * @param $item  int 本人是否参与分红 ，0.参与，1.不参与
     * @param $order
     * @param $setting
     * @param $card
     * @return false|string
     * @throws \think\Exception
     */
    private function getUserMoney($type,$item, $order, $card, $setting){
        $this->log('分红金额计算参数：',[
            'type' => $type,
            'item' => $item,
            'card' =>$card,
            'order_pay_price' => $order['pay_price'],
            'setting' => $setting,

        ]);
        $this->log('分红金额计算-总金额',$order);

        if($type==1){
            //消费分红
            //用户总的分账金额
            $totalUserMoney=bcmul($order['pay_price'],(bcsub($setting['rewardpercent']/100,0.01,2)),2);
        }elseif ($type==2){
            //储值卡分红
            $totalUserMoney=bcmul($order['pay_price'],(bcsub(($card['bonus_percent']/100),0.01,2)),2);//用户总的分账金额
        }

        if($order['pay_price']<$setting['money'] || $item==1){
            $userCount=intval($this->getUserAccounts($order['wxapp_id'],$setting['periods_num']));//分账用户总数,不加支付人
            $this->log('1分红金额计算-总人数计算', $userCount);
        }else{
            $userCount=intval($this->getUserAccounts($order['wxapp_id'],$setting['periods_num']))+1;//分账用户总数,加入本次的出账方一人
            $this->log('2分红金额计算-总人数计算', $userCount);
        }
        if($userCount==0){
            $userMoney=0;//单个用户分账的金额
        }else{
            $this->log('分红金额计算-总金额', $totalUserMoney);
            $this->log('分红金额计算-人数',($userCount ?? 0));
            $this->log('分红金额计算-结果', sprintf("%.3f",($totalUserMoney/$userCount)));
            $userMoney=substr(sprintf("%.3f",($totalUserMoney/$userCount)),0,-1);//单个用户分账的金额
        }


        return $userMoney;//单位分
    }




    /***
     *  统计参与分账的代言人
     * @return bool|int|string
     * @throws \think\Exception
     */
    private function getStoreStaffDivideCount($order){
        return db('store_shop_clerk')->where(array('wxapp_id'=>$order['wxapp_id'],'type'=>1,'shop_id'=>$order['extract_shop_id']))->count();
    }

    /**
     * 统计参与分红的用户
     * @param $wxappId
     * @param $periodsNum
     * @return int|string
     * @throws \think\Exception
     */
    private function getUserAccounts($wxappId,$periodsNum){
        $this->log('0001分红金额计算-人数');
        return db('divide_receives')->where(['wxapp_id'=>$wxappId,'type'=>0,'periods_num'=>$periodsNum])->count();

    }

    /**
     * 获取用户的open_id
     * @param $userId int 用户id
     * @param $wxappId int 微信id
     * @return bool|float|mixed|string|null
     */

    private function getUserOpenId($userId,$wxappId){
        return db('user')->where(['user_id'=>$userId,'wxapp_id'=>$wxappId])->value('open_id');
    }

    /**
     * 获取订单详情
     * @param $orderId
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getOrderInfo($orderId){
        $this->log('899 订单接口入参',$orderId);
        $orderInfo=db('order')->where('order_id',$orderId)->find();
        $this->log('899 订单信息',$orderInfo);
        if($orderInfo['order_source']==40){
            //如果是储值卡，返回合并后的订单储值卡信息
            $orderInfo['card']=db('wxapp_card_order_plan')->where('order_id',$orderId)->find();
            return $orderInfo;
        }elseif($orderInfo['order_source']==50){
            //如果是消费，直接返回订单信息
            return  $orderInfo;
        }elseif ($orderInfo['order_source']==10 && 	$orderInfo['is_fictitious']==1){
            return  $orderInfo;
        }
    }

    /**
     *  获取设置信息
     * @param $wxappId
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getWxappSetting($wxappId){
        return  db('wxapp_setting')->where('wxapp_id',$wxappId)->find();
    }

    /**
     *  获取会员卡的分红设置信息
     * @param $wxappId
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getWxappCardSetting($cardId,$wxappId){
        return  db('wxapp_card')->where(['card_id'=>$cardId,'wxapp_id'=>$wxappId])->find();
    }

    /**
     *  *  查询最后的一条数据
     * @param $setting
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function  getLastUser($setting){
        return db('divide_receives')->where(['wxapp_id'=>$setting['wxapp_id'],'periods_num'=>$setting['periods_num'],'type'=>0])->order('receives_id desc')->limit(1)->find();
    }


    /**
     * 调用退款接口
     * @param $transaction_id
     * @param $payment
     * @param $userMoney
     * @return bool
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function getOneUserBackAbonus($wxappId,$transaction_id,$payment,$userMoney){

        $wxConfig = WxappModel::getWxappRedis($wxappId);

        //获取证书
        if (empty($wxConfig['mchid']) || empty($wxConfig['app_id'])) {
            throw new BaseException(['msg' => '请先到后台小程序设置填写微信支付相关内容']);
        }
        $WxPay = new WxPay($wxConfig);
        return $WxPay->refund($transaction_id,$payment,$userMoney); //用户分红回退
    }
    /**
     *   * 将用户多余的积分给用户加上
     * @param $chage  int 零钱
     * @param $item  int  订单
     * @throws \think\Exception
     */
    private function setUserBlance($chage,$item){
        $userModel=new User();
        $res=$userModel->where('user_id',$item['user_id'])->setInc('balance',$chage);
        if($res){
            // 用户余额变动明细
            BalanceLog::add(50, [
                'user_id'  =>$item['user_id'],
                'money'    =>+$chage,
                'wxapp_id' =>$item['wxapp_id'],
            ], ['order_no' =>$item['order_no']]);
            return $res;
        }

    }

    /**
     *  将用户分不了的金额转化成赏金
     * @param $chage
     * @param $item
     * @throws \think\Exception
     */
    private function setUserDealer($chage,$item){
        $userModel=new \app\common\model\dealer\User();
        $res=$userModel->where(['user_id'=>$item['user_id'],'wxapp_id'=>$item['wxapp_id']])->setInc('money',$chage);
        if($res==1){
            // 用户余额变动明细
            Capital::add([
                'wxapp_id' =>$item['wxapp_id'],
                'user_id'  =>$item['user_id'],
                'flow_type'=>30,
                'money'    =>+$chage,
                'describe' =>'分红转换'
            ]);
            return $res;
        }
    }
}